<template>
  <div class="try-on-container">
    <el-row :gutter="20">
      <!-- 左侧人物上传 -->
      <el-col :span="8">
        <div class="upload-box">
          <h3>输入全身正面照</h3>
          <el-upload
            class="uploader"
            :action="uploadUrl" 
            :show-file-list="false"
            :before-upload="beforePersonUpload"
            :on-success="handlePersonSuccess">
            <img v-if="personUrl" :src="personUrl" class="preview">
            <i v-else class="el-icon-plus uploader-icon"></i>
          </el-upload>
          <div class="tips">请上传符合要求的人物全身照</div>
        </div>
      </el-col>

      <!-- 中间服装上传 -->
      <el-col :span="8">
        <div class="upload-box">
          <h3>输入服装平铺图</h3>
          <el-upload
            class="uploader"
            :action="uploadUrl"
            :show-file-list="false" 
            :before-upload="beforeClothesUpload"
            :on-success="handleClothesSuccess">
            <img v-if="clothesUrl" :src="clothesUrl" class="preview">
            <i v-else class="el-icon-plus uploader-icon"></i>
          </el-upload>
          <div class="tips">请上传符合要求的服装平铺图</div>
        </div>
      </el-col>

      <!-- 右侧生成结果 -->
      <el-col :span="8">
        <div class="result-box">
          <h3>生成试衣效果</h3>
          <div class="result-wrapper">
            <img v-if="resultUrl" :src="resultUrl" class="result-img">
            <div v-else class="placeholder">
              <i class="el-icon-picture-outline"></i>
              <p>上传图片后点击生成</p>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 生成按钮 -->
    <div class="action-bar">
      <el-button type="primary" 
                 :loading="generating"
                 :disabled="!canGenerate"
                 @click="generateResult">
        开始生成
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TryOn',
  
  data() {
    return {
      uploadUrl: '/api/upload', // 文件上传接口
      personUrl: '', // 人物图片URL
      clothesUrl: '', // 服装图片URL  
      resultUrl: '', // 生成结果URL
      generating: false, // 是否正在生成
      taskId: '', // 异步任务ID
      openedMenus: ['1', '2', '3', '4', '5'] // 默认展开所有主菜单
    }
  },

  computed: {
    canGenerate() {
      return this.personUrl && this.clothesUrl && !this.generating
    }
  },

  methods: {
    // 人物图片上传前校验
    beforePersonUpload(file) {
      const isValid = this.validateImage(file)
      if (!isValid) {
        this.$message.error('请上传5KB~5MB的jpg/png/jpeg格式图片')
      }
      return isValid
    },

    // 服装图片上传前校验  
    beforeClothesUpload(file) {
      const isValid = this.validateImage(file)
      if (!isValid) {
        this.$message.error('请上传5KB~5MB的jpg/png/jpeg格式图片')
      }
      return isValid
    },

    // 图片格式校验
    validateImage(file) {
      const isValidFormat = ['image/jpeg', 'image/png'].includes(file.type)
      const isValidSize = file.size / 1024 >= 5 && file.size / 1024 / 1024 <= 5
      return isValidFormat && isValidSize
    },

    // 人物图片上传成功
    handlePersonSuccess(res) {
      this.personUrl = res.url
    },

    // 服装图片上传成功
    handleClothesSuccess(res) {
      this.clothesUrl = res.url  
    },

    // 开始生成
    async generateResult() {
      if(!this.canGenerate) return
      
      this.generating = true
      try {
        // 提交生成任务
        const res = await this.submitTask()
        this.taskId = res.output.task_id
        
        // 轮询任务状态
        this.pollTaskStatus()
      } catch(e) {
        this.$message.error('生成失败:' + e.message)
        this.generating = false
      }
    },

    // 提交生成任务
    async submitTask() {
      const params = {
        model: 'aitryon',
        input: {
          top_garment_url: this.clothesUrl,
          person_image_url: this.personUrl
        },
        parameters: {
          resolution: -1,
          restore_face: true
        }
      }
      
      return await this.$http.post('/api/v1/services/aigc/image2image/image-synthesis', params)
    },

    // 轮询任务状态
    async pollTaskStatus() {
      const timer = setInterval(async () => {
        try {
          const res = await this.$http.get(`/api/v1/tasks/${this.taskId}`)
          const status = res.output.task_status
          
          if(status === 'SUCCEEDED') {
            clearInterval(timer)
            this.resultUrl = res.output.image_url
            this.generating = false
            this.$message.success('生成成功')
          } else if(status === 'FAILED') {
            clearInterval(timer)
            this.generating = false
            this.$message.error('生成失败:' + res.output.message)
          }
        } catch(e) {
          clearInterval(timer)
          this.generating = false
          this.$message.error('查询任务状态失败')
        }
      }, 2000)
    }
  }
}
</script>

<style scoped>
.try-on-container {
  padding: 20px;
}

.upload-box, .result-box {
  text-align: center;
  border: 1px solid #eee;
  padding: 20px;
}

.uploader {
  width: 300px;
  height: 400px;
  margin: 0 auto;
}

.uploader .el-upload {
  width: 100%;
  height: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 400px;
  text-align: center;
}

.preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.result-wrapper {
  width: 300px;
  height: 400px;
  margin: 0 auto;
  border: 1px dashed #d9d9d9;
}

.result-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.action-bar {
  text-align: center;
  margin-top: 30px;
}

.tips {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style> 